// ============================================================ //
// ============================================================ //
//
// @Group       : QiXin Supply Chain Team
// @Author      : ZhiQiang Cheng
// @Date        : 2024-07-11
// @Description : 房间详情: 团购轮次变更,发送一个信号.
//
// ============================================================ //
// ============================================================ //

package job

import (
	"sync/atomic"
	"time"
	"wooha-cache-hub/cache"
	"wooha-cache-hub/dao"

	"github.com/StarfishProgram/starfish-go-sdk/sdklog"
	"github.com/StarfishProgram/starfish-go-sdk/sdktypes"
)

type roomQueue struct{}

var RoomQueue = new(roomQueue)

func (rn *roomQueue) Listen(running *atomic.Bool) {
	for running.Load() {
		roomId, err := cache.PopRoomQueueChannel()
		if err != nil {
			sdklog.Error(err)
			time.Sleep(time.Second)
			continue
		} else if roomId == nil {
			time.Sleep(time.Second)
			continue
		}

		sdklog.Info("房间队列频道:", roomId)
		rn.handle(*roomId)
	}
}

func (rn *roomQueue) handle(roomId sdktypes.ID) {
	room, err := dao.GroupBuyingRoom.GetById(roomId)
	if err != nil {
		sdklog.Error(err)
		return
	} else if room == nil {
		sdklog.Error("房间不存在:", roomId)
		return
	}

	queue, err := dao.GroupBuyingRoomProductQueue.GetInProgressById(roomId)
	if err != nil {
		sdklog.Error(err)
		return
	}

	if err := cache.FlushRoomQueue(roomId, queue); err != nil {
		sdklog.Error(err)
		return
	}

	sdklog.Info("房间队列已刷新:", room.ID)
}
